<template>
  <div class="system-role-container layout-padding">
    <div class="system-role-padding layout-padding-auto">
      <div class="flex_card">
        <el-card class="box-card231">
          <template #header>
            <div
              style="display: flex; align-items: center; position: relative"
              class="card-header"
            >
              <el-icon color="rgb(34, 171, 249)"><Document /></el-icon>
              &nbsp;
              <span style="color: rgb(34, 171, 249)"
                >日压力容器设计质量安全检查</span
              >

              <el-input
                v-model="input_str"
                size="small"
                style="width: 30%; position: absolute; right: 0; top: 0"
                placeholder="请输入名称"
              ></el-input>
            </div>
          </template>
          <el-table
            :height="activeHeight"
            :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
            size="small"
            :data="tableData_getFromBack"
          >
            <el-table-column label="序号" type="index" align="left" />
            <el-table-column
              show-overflow-tooltip
              label="文件编号"
              prop="file_name"
              align="left"
            >
              <template #default="scope">
                <span @click="exportWordDocx_docx_first(scope.row)" class="hober">{{
                  scope.row.file_no || "未填写文件编号"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="填表人"
              prop="modify_user"
              align="left"
            />
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="日期"
              prop="check_time"
              align="left"
            />
            <el-table-column label="操作" prop="create_time" align="left">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="gotoEdit(scope.row)"
                  type="primary"
                  text
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  @click="exportWordDocx_docx_first(scope.row)"
                  type="success"
                  text
                  >下载</el-button
                >

                <el-popconfirm title="确定要删除吗?" @confirm="del_Data(scope.row)">
                  <template #reference>
                    <el-button size="small" type="danger" text>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="box-card231">
          <template #header>
            <div
              style="display: flex; align-items: center; position: relative"
              class="card-header"
            >
              <el-icon color="#95d475"><Document /></el-icon>
              &nbsp;
              <span style="color: #95d475">周压力容器设计质量安全排查治理报告</span>

              <el-input
                v-model="input_str_third"
                size="small"
                style="width: 30%; position: absolute; right: 0; top: 0"
                placeholder="请输入名称"
              ></el-input>
            </div>
          </template>
          <el-table
            :height="activeHeight"
            :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
            size="small"
            :data="tableData2"
          >
            <el-table-column label="序号" type="index" align="left" />
            <el-table-column
              show-overflow-tooltip
              label="文件编号"
              prop="file_name"
              align="left"
            >
              <template #default="scope">
                <span @click="exportWordDocx_docx(scope.row)" class="hober">{{
                  scope.row.file_no || "未填写文件编号"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="填表人"
              prop="modify_user"
              align="left"
            />
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="日期"
              prop="report_time"
              align="left"
            />
            <el-table-column label="操作" prop="create_time" align="left">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="gotoEdit_row(scope.row)"
                  type="primary"
                  text
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  @click="exportWordDocx_docx(scope.row)"
                  type="success"
                  text
                  >下载</el-button
                >
                <el-popconfirm title="确定要删除吗?" @confirm="del_PressureVesselQSWeeksGovernRecord(scope.row)">
                  <template #reference>
                    <el-button size="small" type="danger" text>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="box-card231">
          <template #header>
            <div
              style="display: flex; align-items: center; position: relative"
              class="card-header"
            >
              <el-icon color="rgb(245, 108, 108)"><Document /></el-icon>
              &nbsp;
              <span style="color: rgb(245, 108, 108)"
                >月压力容器设计质量安全调度会会议纪要</span
              >

              <el-input
                v-model="input_str_second"
                size="small"
                style="width: 30%; position: absolute; right: 0; top: 0"
                placeholder="请输入名称"
              ></el-input>
            </div>
          </template>
          <el-table
            :height="activeHeight"
            :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
            size="small"
            :data="tableData3"
          >
            <el-table-column label="序号" type="index" align="left" />
            <el-table-column
              show-overflow-tooltip
              label="文件编号"
              prop="file_name"
              align="left"
            >
              <template #default="scope">
                <span @click="exportWordDocx_docx_third(scope.row)" class="hober">{{
                  scope.row.file_no || "未填写文件编号"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="填表人"
              prop="modify_user"
              align="left"
            />
            <el-table-column
              show-overflow-tooltip
              width="100"
              label="日期"
              prop="meeting_time"
              align="left"
            />
            <el-table-column label="操作" prop="create_time" align="left">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="gotoEdit_third(scope.row)"
                  type="primary"
                  text
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  @click="exportWordDocx_docx_third(scope.row)"
                  type="success"
                  text
                  >下载</el-button
                >
                <el-popconfirm title="确定要删除吗?" @confirm="del_DelPressureVesselQSSchedulingMettingRecord(scope.row)">
                  <template #reference>
                    <el-button size="small" type="danger" text>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-dialog width="55%" v-model="editdia_both">
          <div style="height: 800px">
            <checkFileWrite
              view="日压力容器设计质量安全检查"
              @tableData="getTableData_com"
              @sendSuccess2="sendSuccessEdit_getData"
              @sendSuccess="sendSuccess_edit"
              :editData="editData_both"
            ></checkFileWrite>
          </div>
        </el-dialog>

        <el-dialog width="50%" v-model="editdia2">
          <div style="height: 800px">
            <checkFileWrite
              view="压力容器设计质量安全排查治理报告"
              @tableData="getTableData_getValue"
              @sendSuccess="sendSuccess2"
              :editData="editData_both"
            ></checkFileWrite>
          </div>
        </el-dialog>

        <el-dialog width="50%" v-model="editdia3">
          <div style="height: 800px">
            <checkFileWrite
              view="月压力容器设计质量安全调度会会议纪要"
              @tableData="getTableData3"
              @sendSuccess="sendSuccess3"
              :editData="editData_both"
            ></checkFileWrite>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import checkFileWrite from "./checkFileWirteCom.vue";
import { ref, onMounted, watch } from "vue";
import {
  CreatePressureVesselQSDialyCheckRecord,
  SavePressureVesselQSWeeksGovernRecord,
  GetAllPressureVesselQSDialyCheckRecord,
  GetAllPressureVesselQSWeeksGovernRecord,
  GetAllPressureVesselQSSchedulingMettingRecord,
  DelPressureVesselQSDialyCheckRecord,
  DelPressureVesselQSWeeksGovernRecord,
  DelPressureVesselQSSchedulingMettingRecord,
} from "../../api/projectManage/projectList";
import { ElMessage } from "element-plus";
import { Document } from "@element-plus/icons-vue";
import JSZipUtils from "jszip-utils";
import docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import JSZip from "pizzip";
import ImageModule from "docxtemplater-image-module-free";

let editdia_both = ref(false);
let editData_both = ref({});

// 编辑
let gotoEdit = (data) => {
  editData_both.value = { ...data };
  editdia_both.value = true;
};

// 删除
let del_Data = async (data) => {
  await DelPressureVesselQSDialyCheckRecord({ ...data });
  ElMessage.success("删除成功");
  getTableFirstData();
};

// 获取新数据
let getTableData_com = (data) => {
  tableData_getFromBack.value = data;
  ElMessage.success("修改成功");
};

// 编辑弹窗消失
let sendSuccess_edit = () => {
  editdia_both.value = false;
};


// 编辑完成
let sendSuccessEdit_getData = () => {
  editdia_both.value = false;
  getTableFirstData();
};

// 获取新数据
let getTableData_getValue = (data) => {
  tableData2.value = data;
  ElMessage.success("修改成功");
};

let sendSuccess2 = () => {
  editdia2.value = false;
};

let getTableData3 = (data) => {
  tableData3.value = data;
  ElMessage.success("修改成功");
};
let sendSuccess3 = () => {
  editdia3.value = false;
};

let del_PressureVesselQSWeeksGovernRecord = async (data) => {
  await DelPressureVesselQSWeeksGovernRecord({ ...data });
  ElMessage.success("删除成功");
  getTableSecondData();
};

let del_DelPressureVesselQSSchedulingMettingRecord = async (data) => {
  await DelPressureVesselQSSchedulingMettingRecord({ ...data });
  ElMessage.success("删除成功");
  getTableThirdData();
};

let editdia2 = ref(false);
let gotoEdit_row = (data) => {
  editData_both.value = { ...data };
  editdia2.value = true;
};

let editdia3 = ref(false);
let gotoEdit_third = (data) => {
  editData_both.value = { ...data };
  editdia3.value = true;
};

let getYearMonthAndWeekNumber = (dateString) => {
  // 解析日期字符串到Date对象
  const date = new Date(dateString);

  // 获取年份和月份（月份从0开始，所以需要+1）
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  // 计算是一年中的第几周
  // 1. 计算该日期是一年中的第几天
  const dayOfYear =
    Math.floor((date - new Date(year, 0, 1)) / 1000 / 60 / 60 / 24) + 1;

  // 2. 计算是第几周，ISO 8601标准下，一周的第一天是周一
  const weekNumber = Math.ceil((dayOfYear - 1) / 7);

  // 返回结果
  return {
    year: year,
    month: month,
    week: weekNumber,
  };
};

let exportWordDocx_docx = (obj) => {
  const url = "/mouth.docx";
  JSZipUtils.getBinaryContent(url, (err, data) => {
    if (err) {
      ElMessage.error("导出报告出错");
      console.log("err:", err);
      return;
    }
    let zip = new JSZip(data);
    const Docxtemplater = docxtemplater;
    const imageOptions = {
      centered: false,
      getImage(tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      },
      getSize(img, tagValue, tagName) {
        // 非固定大小（这里是设置宽度最大为500px的图片）
        return new Promise(function (resolve, reject) {
          let image = new Image();
          image.src = tagValue;
          let imgWidth, imgHeight, scale;
          image.onload = function () {
            imgWidth = image.width;
            imgHeight = image.height;
            scale = 0;
            if (imgWidth > 500) {
              scale = 500 / imgWidth;
              imgWidth = 500;
              imgHeight = imgHeight * scale;
            }
            resolve([imgWidth, imgHeight]);
          };
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            reject(e);
          };
        });
      },
    };

    const nullGetter = (part, scopeManager) => {
      if (!part.module) {
        return "";
      }
    };

    let doc = new Docxtemplater(zip, {
      linebreaks: true,
      nullGetter: nullGetter,
      modules: [new ImageModule(imageOptions)],
    });
    // 将模板字符 和 创建的obj中的键名对应并且赋值
    let reportInfo = {};
    obj.year = getYearMonthAndWeekNumber(obj.report_time).year;
    obj.month = getYearMonthAndWeekNumber(obj.report_time).month;
    obj.week = getYearMonthAndWeekNumber(obj.report_time).week;
    obj.create_time = obj.report_time;
    obj.years = obj.create_time.split("-")[0];
    obj.months = obj.create_time.split("-")[1];
    obj.days = obj.create_time.split("-")[2];
    if (obj.item3_value) {
      obj.item3_value_1 = true;
      obj.item3_value_2 = false;
    } else {
      obj.item3_value_1 = false;
      obj.item3_value_2 = true;
    }
    reportInfo = { ...obj };
    doc.resolveData({ ...reportInfo }).then(() => {
      doc.render();
      let out = doc.getZip().generate({
        type: "blob",
        MimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      // saveAs(out, "周压力容器设计质量安全排查治理报告.docx");
       saveAs(out, `${obj.file_no}.docx`);
    });
  });
};

let exportWordDocx_docx_third = (obj) => {
  const url = "/meeting.docx";
  JSZipUtils.getBinaryContent(url, (err, data) => {
    if (err) {
      ElMessage.error("导出报告出错");
      console.log("err:", err);
      return;
    }
    let zip = new JSZip(data);
    const Docxtemplater = docxtemplater;
    const imageOptions = {
      centered: false,
      getImage(tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      },
      getSize(img, tagValue, tagName) {
        // 非固定大小（这里是设置宽度最大为500px的图片）
        return new Promise(function (resolve, reject) {
          let image = new Image();
          image.src = tagValue;
          let imgWidth, imgHeight, scale;
          image.onload = function () {
            imgWidth = image.width;
            imgHeight = image.height;
            scale = 0;
            if (imgWidth > 500) {
              scale = 500 / imgWidth;
              imgWidth = 500;
              imgHeight = imgHeight * scale;
            }
            resolve([imgWidth, imgHeight]);
          };
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            reject(e);
          };
        });
      },
    };

    const nullGetter = (part, scopeManager) => {
      if (!part.module) {
        return "";
      }
    };

    let doc = new Docxtemplater(zip, {
      linebreaks: true,
      nullGetter: nullGetter,
      modules: [new ImageModule(imageOptions)],
    });
    let reportInfo = {};
    obj.year = getYearMonthAndWeekNumber(obj.meeting_time).year;
    obj.month = getYearMonthAndWeekNumber(obj.meeting_time).month;
    obj.week = getYearMonthAndWeekNumber(obj.meeting_time).week;
    obj.create_time = obj.meeting_time;

    reportInfo = { ...obj };
    doc.resolveData({ ...reportInfo }).then(() => {
      doc.render();
      let out = doc.getZip().generate({
        type: "blob",
        MimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      // saveAs(out, "月压力容器设计质量安全调度会会议纪要.docx");
      saveAs(out, `${obj.file_no}.docx`);
    });
  });
};

let exportWordDocx_docx_first = (obj) => {
  const url = "/day.docx";
  JSZipUtils.getBinaryContent(url, (err, data) => {
    if (err) {
      ElMessage.error("导出报告出错");
      console.log("err:", err);
      return;
    }
    let zip = new JSZip(data);
    const Docxtemplater = docxtemplater;
    const imageOptions = {
      centered: false,
      getImage(tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      },
      getSize(img, tagValue, tagName) {
        // 非固定大小（这里是设置宽度最大为500px的图片）
        return new Promise(function (resolve, reject) {
          let image = new Image();
          image.src = tagValue;
          let imgWidth, imgHeight, scale;
          image.onload = function () {
            imgWidth = image.width;
            imgHeight = image.height;
            scale = 0;
            if (imgWidth > 500) {
              scale = 500 / imgWidth;
              imgWidth = 500;
              imgHeight = imgHeight * scale;
            }
            resolve([imgWidth, imgHeight]);
          };
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            reject(e);
          };
        });
      },
    };

    const nullGetter = (part, scopeManager) => {
      if (!part.module) {
        return "";
      }
    };

    let doc = new Docxtemplater(zip, {
      linebreaks: true,
      nullGetter: nullGetter,
      modules: [new ImageModule(imageOptions)],
    });
    let reportInfo = {};
    obj.create_time = obj.check_time;
    reportInfo = { ...obj };
    doc.resolveData({ ...reportInfo }).then(() => {
      doc.render();
      let out = doc.getZip().generate({
        type: "blob",
        MimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      // saveAs(out, "每日压力容器设计质量安全检查记录表.docx");
      saveAs(out, `${obj.file_no}.docx`);
    });
  });
};

let input_str = ref("");
let input_str_third = ref("");
let input_str_second = ref("");
watch(input_str, async () => {
  if (input_str.value) {
    let res = await GetAllPressureVesselQSDialyCheckRecord();
    let data = JSON.parse(JSON.stringify(res));
    tableData_getFromBack.value = data.filter((v) => v.file_no?.includes(input_str.value));
  } else {
    getTableFirstData();
  }
});

watch(input_str_third, async () => {
  if (input_str_third.value) {
    let res = await GetAllPressureVesselQSWeeksGovernRecord();
    let data = JSON.parse(JSON.stringify(res));
    tableData2.value = data.filter((v) =>
      v.file_no?.includes(input_str_third.value)
    );
  } else {
    getTableSecondData();
  }
});

watch(input_str_second, async () => {
  if (input_str_second.value) {
    let res = await GetAllPressureVesselQSSchedulingMettingRecord();
    let data = JSON.parse(JSON.stringify(res));
    tableData3.value = data.filter((v) =>
      v.file_no?.includes(input_str_second.value)
    );
  } else {
    getTableThirdData();
  }
});

let activeHeight = ref(0);
onMounted(() => {
  getTableFirstData();
  getTableSecondData();
  getTableThirdData();
  activeHeight.value = `${
    document.querySelector(".system-role-container").clientHeight - 90
  }px`;

  window.addEventListener("resize", () => {
    activeHeight.value = `${
      document.querySelector(".system-role-container").clientHeight - 90
    }px`;
  });
});

let tableData_getFromBack = ref([]);
let getTableFirstData = async () => {
  let res = await GetAllPressureVesselQSDialyCheckRecord();

  res.sort((a, b) => {
    return new Date(a.check_time) - new Date(b.check_time);
  });

  tableData_getFromBack.value = res;
};

let tableData2 = ref([]);
let getTableSecondData = async () => {
  let res = await GetAllPressureVesselQSWeeksGovernRecord();
  res.sort((a, b) => {
    return new Date(a.report_time) - new Date(b.report_time);
  });
  tableData2.value = res;
};

let tableData3 = ref([]);
let getTableThirdData = async () => {
  let res = await GetAllPressureVesselQSSchedulingMettingRecord();
  res.sort((a, b) => {
    return new Date(a.meeting_time) - new Date(b.meeting_time);
  });
  tableData3.value = res;
};
</script>

<style lang="scss" scoped>
.button_ab {
  position: absolute;
  right: 20px;
  bottom: -20px;
}
.BT_title {
  margin-bottom: 10px;
  text-align: center;
  font-size: 22px;
  font-weight: bold;
}
.display_flex {
  width: 100%;
  display: flex;
  align-items: center;
}

.flex_card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .hober {
    cursor: pointer;
  }
  .hober:hover {
    color: rgb(34, 171, 249);
    text-decoration: underline;
  }

  .card-header {
    display: flex;
    align-items: center;
    font-size: 17px;
    span {
      border-radius: 4px;

      font-weight: 600;
    }
  }

  .project-info {
    display: flex;
    font-size: 14px;

    flex-direction: column;
    .project-info-item {
      margin-bottom: 10px;
    }
  }

  .box-card231 {
    width: 33%;
    ::v-deep(.el-card__body) {
      padding: 5px;
    }
  }
}
</style>
